package handler

import (
	"bytes"
	"os"
	"os/exec"

	"github.com/gin-gonic/gin"

	"gitee.com/goframe/lt-collector/libs/libce"
	"gitee.com/goframe/lt-collector/libs/libgin"
	"gitee.com/goframe/lt-collector/libs/orma"
	"gitee.com/goframe/lt-collector/model"
)

var (
	SetHandler Setting
)

type (
	Setting map[string]string
)

func (h Setting) Reboot() gin.HandlerFunc {
	return libgin.Return.WarpHandler(func(c *gin.Context) (err error) {
		bts := make([]byte, 0)
		cmdIO := bytes.NewBuffer(bts)
		cmdPointer := exec.Command(os.Args[0], "restart")
		cmdPointer.Stdout = cmdIO
		cmdPointer.Stderr = cmdPointer.Stdout
		if err = cmdPointer.Start(); err != nil {
			return
		}
		libgin.Return.GinOK(c, gin.H{"information": cmdIO.String()})
		return
	})
}

func (h Setting) ClearCache() gin.HandlerFunc {
	return libgin.Return.WarpHandler(func(c *gin.Context) (err error) {
		libce.Cache.Flush()
		libgin.Return.GinOK(c, "OK")
		return
	})
}

func (h Setting) PUT() gin.HandlerFunc {
	return libgin.Return.WarpHandler(h.put)
}

func (h Setting) put(c *gin.Context) (err error) {
	bindBean := new(Setting)
	if err = c.ShouldBind(bindBean); err != nil {
		return
	}
	sn := orma.GetEngine().NewSession()
	if err = sn.Begin(); err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = sn.Rollback()
		}
		sn.Close()
	}()
	beans := make([]*model.SysSetting, 0, 1)
	for key, value := range *bindBean {
		md := new(model.SysSetting)
		md.SetSession(sn)
		err = md.GetByKey(key)
		if err == orma.ErrOrmNotFound {
			md.Key = key
			md.Value = value
			if err = orma.NormalInsert(sn.InsertOne(md)); err != nil {
				return
			}
			continue
		}
		if err != nil {
			return err
		}
		md.Value = string(value)
		err = orma.NormalUpdate(sn.ID(md.ID).ForUpdate().Update(md))
		if err != nil {
			return
		}
		beans = append(beans, md)
	}
	if err = sn.Commit(); err != nil {
		return
	}
	libgin.Return.GinOK(c, beans)
	return
}
